package com.happy.ibidding.controller;

import com.happy.ibidding.bean.ApiResponse;
import com.happy.ibidding.bean.User;
import com.happy.ibidding.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("api/user")
public class UserController {

    final private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("login")
    public ApiResponse<User> login(String userId, String password) {

        if(userId.equals("admin") && password.equals("admin123")){
            return ApiResponse.<User>builder().data(User.builder()
                    .userId("user_admin")
                    .admin(true)
                    .name("Root user")
                    .password("admin123")
                    .id("user_admin")
                    .address("No where")
                    .company("Ibidding")
                    .email("admin@ibidding.com")
                    .mobile("no")
                    .sex("Other")
                    .build()).build();
        }


        User user = this.userService.findUserByUserId(userId);

        if (Objects.nonNull(user) && user.getPassword().equals(password)) {
            return ApiResponse.<User>builder().data(user).build();
        } else {
            return ApiResponse.<User>builder().errorMessage("User Name or password error").success(false).build();
        }

    }

    @GetMapping("all")
    public List<User> viewAll() {
        return this.userService.viewAllUsers();
    }

    @GetMapping("/delete/{mongodbId}")
    public void deleteUser(@PathVariable String mongodbId) {
        this.userService.deleteUser(mongodbId);
    }

    @PostMapping("register")
    public ApiResponse<User> register(@RequestBody User user) {

        if (Objects.nonNull(this.userService.findUserByUserId(user.getUserId()))) {
            return ApiResponse.<User>builder().errorMessage("User Name already exist").success(false).build();
        } else {
            user.setRegisterTime(System.currentTimeMillis());

            return ApiResponse.<User>builder().data(this.userService.saveUser(user)).build();
        }
    }

    @PostMapping("update")
    public ApiResponse<User> update(@RequestBody User user) {
        if (Objects.isNull(this.userService.findUserByUserId(user.getUserId()))) {

            return ApiResponse.<User>builder().errorMessage("User doesn't exist").success(false).build();
        } else {

            return ApiResponse.<User>builder().data(this.userService.saveUser(user)).build();
        }
    }

    @GetMapping("{mongodbId}")
    public User viewUser(@PathVariable String mongodbId){
        return this.userService.findUserById(mongodbId);
    }

}
